<?
abstract class dbdController
{
	private $app_dir = null;
	protected $router = null;
	protected $model = null;
	protected $view = null;
	protected $xajax = null;
	protected $xajaxResponse = null;
	private $template = null;
	private $default_render = true;

	final public function __construct(dbdRouter $router, $app_dir)
	{
		$this->app_dir = $app_dir;
		$this->router = $router;
		$this->view = new dbdSmarty($this->app_dir);
		$this->view->assign("app_name", dbdMVC::getAppName());
		$this->init();
	}

	protected function init()
	{}

	public function doDefault()
	{}

	protected function setTemplate($tpl)
	{
		$this->template = $tpl;
	}

	protected function noRender()
	{
		$this->default_render = false;
	}

	protected function assignAllParams()
	{
		$this->view->assign(stripslashes($this->getParams()));
	}

	final protected function registerXajaxActions($controller = null)
	{
		if ($controller == null)
			$controller = $this->getController();
		if ($this->xajax == null)
			$this->xajax = new dbdXajax($this->router, dbdURI::create($controller, "xajax"), dbdDispatcher::XAJAX_ACTION_PREFIX);
		foreach (get_class_methods($this->getController()) as $m)
		{
			if (preg_match("/^".dbdDispatcher::XAJAX_ACTION_PREFIX."[A-Z]/", $m))
			{
				$m2 = preg_replace("/^".dbdDispatcher::XAJAX_ACTION_PREFIX."([A-Z])/", "$1", $m);
				$this->xajax->registerFunction(array($m2, $this, $m));
			}
		}
		$this->view->assign("xajax", $this->xajax->getJavascript("/", "dbdXajaxJS/"));
	}

	final public function __destruct()
	{
		if (!$this->view->wasRendered() && $this->default_render)
		{
			if (!$this->template)
				$this->template = preg_replace("/^([A-Z]{1})(.*)$/e", "strtolower('$1').$2", $this->router->getController().".tpl");
			if (!$this->view->template_exists($this->template))
				throw new dbdException("View (".$this->template.") could not be found!");
			$this->view->display($this->template);
		}
	}

	final public function doXajax()
	{
		$this->noRender();
		$this->registerXajaxActions();
		$this->xajaxResponse = new xajaxResponse();
		$this->xajax->processRequests();
	}

	protected function forward($url = "/")
	{
		header("Location: ".$url);
		$this->noRender();
	}

	protected function getAppDir()
	{
		return $this->app_dir;
	}

	protected function getController()
	{
		return $this->router->getController();
	}

	protected function getAction()
	{
		return $this->router->getAction();
	}

	protected function setParam($name, $value)
	{
		return $this->router->setParam($name, $value);
	}

	protected function getParam($name)
	{
		return $this->router->getParam($name);
	}

	protected function getParams()
	{
		return $this->router->getParams();
	}

	protected function getURL($get_params = false)
	{
		return $this->router->getURL($get_params);
	}
}
?>